package com.hnucm.c201901020121.Activity;

import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.hnucm.c201901020121.R;
import com.hnucm.c201901020121.Utils.Bmob.BMyTask;
import com.hnucm.c201901020121.Utils.Bmob.BmobTask;
import com.hnucm.c201901020121.Utils.OtherUtils.GlideEngine;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import static com.hnucm.c201901020121.Activity.LoginAct.currentUser;

public class TaskAuditAct extends AppCompatActivity {
    ImageView back, headImg, img, addImg;
    TextView taskid, label, amount, garaAmount, taskTime, audioTime, step1, step2, step3, step3Detail, title, step1Detail;
    TextView first, second, third;
    Button auditSuccess, auditFail;
    String publisherId, realPathFromUri, suHeadImg;
    private String imgFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_audit);
        initView();
        getDate();
        first.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
        second.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
        third.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD_ITALIC);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        auditSuccess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateMytaskState("已完成");
                updateTaskDate("已完成");
                Toast.makeText(TaskAuditAct.this,"审核成功",Toast.LENGTH_LONG).show();
                finish();
            }
        });
        auditFail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateMytaskState("不合格");
                Toast.makeText(TaskAuditAct.this,"审核失败",Toast.LENGTH_LONG).show();
                finish();
            }
        });
        addImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(TaskAuditAct.this)
                        .openGallery(PictureMimeType.ofImage())
                        .imageEngine(GlideEngine.createGlideEngine())
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(List<LocalMedia> result) {
                                // onResult Callback

                                for (LocalMedia localMedia : result) {
                                    Log.i("MainActivity", localMedia.getPath());
                                }
                                //todo 显示图片
                                Glide.with(TaskAuditAct.this).load(Uri.fromFile(new File(result.get(0).getRealPath())))
                                        .into(addImg);
                                realPathFromUri = result.get(0).getRealPath();
                            }

                            @Override
                            public void onCancel() {
                                // onCancel Callback
                            }
                        });
            }
        });
    }

    void initView() {
        addImg = findViewById(R.id.imageView67);
        first = findViewById(R.id.imageView54);
        second = findViewById(R.id.imageView55);
        third = findViewById(R.id.imageView58);
        back = findViewById(R.id.back);
        headImg = findViewById(R.id.headimg);
        img = findViewById(R.id.img);
        taskid = findViewById(R.id.taskId);
        label = findViewById(R.id.label);
        amount = findViewById(R.id.amount);
        garaAmount = findViewById(R.id.guaraAmount);
        taskTime = findViewById(R.id.taskTime);
        step1Detail = findViewById(R.id.textView108);
        audioTime = findViewById(R.id.audioTime);
        title = findViewById(R.id.title1);
        step1 = findViewById(R.id.step1);
        step2 = findViewById(R.id.step2);
        step3 = findViewById(R.id.step3);
        step3Detail = findViewById(R.id.step4);
        auditSuccess = findViewById(R.id.button2);
        auditFail=findViewById(R.id.button5);
    }

    private void insertData() {
        if (auditSuccess.getText().equals("点击报名")) {
            BMyTask bMyTask = new BMyTask();
            SimpleDateFormat formatter = new SimpleDateFormat("MM-dd HH:mm");
            Date curDate = new Date(System.currentTimeMillis());
            String time = formatter.format(curDate);
            Log.i("time", time);
            updateTaskDate("已领取");
            updateTaskOrderTakeId(currentUser.getObjectId());
            bMyTask.setPublisherId(publisherId);
            bMyTask.setOrderTackerId(currentUser.getObjectId());
            bMyTask.setState("待提交");
            bMyTask.setAmount(amount.getText().toString());
            bMyTask.setLabel(label.getText().toString());
            bMyTask.setTitle(title.getText().toString());
            bMyTask.setHeadimg(suHeadImg);
            bMyTask.setTaskId(taskid.getText().toString());
            bMyTask.setTime(time);
            bMyTask.save(new SaveListener<String>() {
                @Override
                public void done(String s, BmobException e) {
                    if (e == null) {
                        Toast.makeText(TaskAuditAct.this, "报名成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(TaskAuditAct.this, "您已报名该任务", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
        if (auditSuccess.getText().equals("点击提交")) {
            updateTaskDate("审核中");
            if (realPathFromUri != null) {
                uploadfile(realPathFromUri);
            } else {
                Toast.makeText(TaskAuditAct.this, "请选择要提交的图片", Toast.LENGTH_LONG).show();
            }
            updateImg("http://192.168.43.173:8080/FileUpload/upload/" + imgFile);
            updateMytaskState("审核中");
            Toast.makeText(TaskAuditAct.this, "提交成功", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    private void updateTaskDate(String data) {
        BmobTask bmobTask = new BmobTask();
        bmobTask.setState(data);
        bmobTask.update(taskid.getText().toString(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.i("upda", "x修改成功");
                } else {
                }
            }

        });
    }

    private void updateTaskOrderTakeId(String data) {
        BmobTask bmobTask = new BmobTask();
        bmobTask.setOrderTackerId(data);
        bmobTask.update(taskid.getText().toString(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.i("upda", "x修改成功");
                } else {
                }
            }

        });
    }

    private void updateImg(String data) {
        BmobTask bmobTask = new BmobTask();
        bmobTask.setSubmitedImg(data);
        bmobTask.update(taskid.getText().toString(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.i("upda", "x修改成功");
                } else {
                }
            }
        });
    }

    private void updateMytaskState(String data) {
        BMyTask bMyTask = new BMyTask();
        bMyTask.setState(data);
        String myTaskId = getIntent().getStringExtra("myTaskId");
        Log.i("id", myTaskId);
        bMyTask.update(myTaskId, new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.i("upda", "x修改成功");
                } else {

                }
            }
        });
    }

    private void getDate() {
        String id = getIntent().getStringExtra("taskId");
        Log.i("bmob", id);
        BmobQuery<BmobTask> bmobQuery = new BmobQuery<BmobTask>();
        bmobQuery.getObject(id, new QueryListener<BmobTask>() {
            @Override
            public void done(BmobTask object1, BmobException e) {
                if (e == null) {
                    Glide.with(TaskAuditAct.this).load(object1.getHeadimg()).into(headImg);
                    taskid.setText(object1.getObjectId());
                    label.setText(object1.getLabel());
                    amount.setText(object1.getAmount());
                    garaAmount.setText(object1.getGaraMount());
                    taskTime.setText(object1.getTaskTime());
                    audioTime.setText(object1.getAudioTime());
                    title.setText(object1.getTitle());
                    step1.setText(object1.getStep1());
                    step2.setText(object1.getStep2());
                    step3.setText(object1.getStep3());
                    step3Detail.setText(object1.getStep3Detail());
                    step1Detail.setText(object1.getStep1Detail());
                    publisherId = object1.getPublisherId();
                    Glide.with(TaskAuditAct.this).load(object1.getSubmitedImg()).into(addImg);
                    Glide.with(TaskAuditAct.this).load(object1.getImg()).into(img);
                    suHeadImg = object1.getHeadimg();
                } else {

                }
            }
        });
    }

    private void uploadfile(String url) {
        RequestParams params = new
                RequestParams("http://192.168.43.173:8080/FileUpload/FileUploadServlet"
        );
        //// 使用 multipart 表单上传文件
        params.setMultipart(true);
        String prefix = UUID.randomUUID().toString().replace("-", "");
        imgFile = prefix + ".jpg";
        params.addBodyParameter("file", new
                        File(url),
                null, imgFile);

        Log.i("upload", Environment.getExternalStorageDirectory().toString());
        x.http().post(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(File result) {
                Log.i("onSuccess-上传文件成功", result.toString());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtil.e("onError-下载文件失败" + ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtil.e("onCancelled-");
            }

            @Override
            public void onFinished() {
                LogUtil.e("onFinished-");
            }

            @Override
            public void onWaiting() {
                LogUtil.e("onWaiting-");
            }

            @Override
            public void onStarted() {
                LogUtil.e("onStarted-");
            }

            @Override
            public void onLoading(long total, long current, boolean
                    isDownloading) {
//                progressBar.setMax((int) total);
//                progressBar.setProgress((int) current);
                LogUtil.e("onLoading-" + current + "/" + total);
            }
        });
    }
}
